#!/usr/bin/env python

from optparse import OptionParser
import utils
import sys

CHARSET = sys.stdin.encoding

def main():

	parser = OptionParser(description="Help building vanilla extension.",
						  prog=sys.argv[0],
						  version="0.1b",
						  usage='%prog [options] create "extensionname" | build')
	
	parser.add_option("-r", "--root",
					  dest="root",
					  help="The extension directory that should contain a default.php file.",
					  default="./", nargs=1)
	parser.add_option("-q", "--quiet",
					  action="store_const", const=50, default=20, dest="logger_level",
					  help="Won't print any message.")
	parser.add_option("--debug",
					  action="store_const", const=10, dest="logger_level",
					  help="Will display some debigging information.")
	parser.add_option("-m", "--no-minify",
					  action="store_false", default=True, dest="minify",
					  help="Disable compression of css and js files.")
	parser.add_option("-n", "--no-interaction",
					  action="store_false", default=True, dest="pause",
					  help="Won't prompt.")
	
	(options, args) = parser.parse_args()

	if len(args) < 1 or not args[0] in ('create','build',):
		fail(parser.print_help(), pause=options.pause)

	root = unicode(options.root, CHARSET)
	
	if args[0] == 'create':
		if len(args) < 2:
			fail("You have to specify a name for your extension.", code=2
				 , pause=options.pause)
		else:
			ext_name = unicode(args[1], CHARSET)
		try:
			creator = utils.Creator(ext_name, base_dir=root, logger_level=options.logger_level)
			creator.create()
			success(pause=options.pause)
		except utils.UtilsError, e:
			fail("Extension creation failed: %s" % str(e), code=4, pause=options.pause)
	else:
		try:
			setup = utils.Builder(base_dir=root,
								  logger_level=options.logger_level,
								  minify=options.minify)
			setup.build()
			success(pause=options.pause)
		except utils.UtilsError, e:
			fail("Build failed: %s" % str(e), code=3, pause=options.pause)
	

def fail(message=None, code=1, pause=False):
	if message:
		message = message.encode(CHARSET)
		sys.stderr.write(message + '\n')
	if pause:
		try:
			raw_input('Press enter to exit...')
		except EOFError:
			pass
	exit(code)

def success(message=None, pause=False):
	if message:
		message = message.encode(CHARSET)
		print message
	if pause:
		try:
			raw_input('Press enter to exit...')
		except EOFError:
			pass

if __name__ == '__main__':
	main()